<script setup>
import { reactive, computed } from 'vue'
const state = reactive({
  list: [
    { id: 1, name: '吃饭', doned: true },
    { id: 2, name: '睡觉', doned: false },
    { id: 3, name: '打豆豆', doned: true },
  ],
  todoName: '',
})

const handleDel = (id) => (state.list = state.list.filter((item) => item.id !== id))

const handleAdd = () => {
  if (state.todoName.trim().length === 0) return alert('不能为空')
  const item = {
    id: Date.now(),
    name: state.todoName,
    doned: false,
  }
  state.list.unshift(item)
  state.todoName = ''
}

// 剩余数量
const leftCount = computed(() => state.list.filter((item) => !item.doned).length)
// 是否展示底部栏
const isShowFooter = computed(() => !(state.list.length === 0))
// 存在一个已完成的就显示，就返回 true
const isShowClear = computed(() => state.list.some((item) => item.doned))
// 清空已完成
const clearComputed = () => (state.list = state.list.filter((item) => !item.doned))
</script>
<template>
  <section class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <input class="new-todo" placeholder="What needs to be done?" autofocus v-model="state.todoName" @keyup.enter="handleAdd" />
    </header>

    <section class="main">
      <input id="toggle-all" class="toggle-all" type="checkbox" />
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list">
        <!-- 有 completed 就划线 -->
        <li
          :class="{
            // 右边为 true，就是用左边的 class
            completed: item.doned,
          }"
          v-for="item in state.list"
          :key="item.id"
        >
          <div class="view">
            <!-- v-model 对应的值是 true，就会自动打钩，内部会把 checked 变为 true -->
            <input class="toggle" type="checkbox" v-model="item.doned" />
            <label>{{ item.name }}</label>
            <button class="destroy" @click="handleDel(item.id)"></button>
          </div>
          <input class="edit" value="Create a TodoMVC template" />
        </li>
      </ul>
    </section>

    <footer class="footer" v-if="isShowFooter">
      <span class="todo-count"
        ><strong>{{ leftCount }}</strong> item left</span
      >
      <ul class="filters">
        <li>
          <a class="selected" href="#/">All</a>
        </li>
        <li>
          <a href="#/active">Active</a>
        </li>
        <li>
          <a href="#/completed">Completed</a>
        </li>
      </ul>
      <button class="clear-completed" v-if="isShowClear" @click="clearComputed">Clear completed</button>
    </footer>
  </section>
</template>
